package
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;

	public class ImageManager
	{
		private static var imageCounter:int = 0;
		private static var bitmapDataCache:Object = new Object();
		private static var onCompleteCallback:Function;
		
		public function ImageManager()
		{
		}
		
		public static function getImage(url:String):DisplayObject{
			return new Bitmap(bitmapDataCache[Game.clientFilesPath + url] as BitmapData);
		}
		
		public static function getImages():Array{
			var images:Array = [
				'assets/buttons/shopping_cart.png',
				'assets/cloud.png',
				'assets/grass_block3.png',
				'assets/shopper1_sheet.png',
				'assets/coins.png',
				'assets/tree.png',
				'assets/profile_pics/brian_r.jpg',
				'assets/profile_pics/helen_z.jpg',
				'assets/profile_pics/jesse_smith.jpg',
				'assets/profile_pics/mark_n.jpg',
				'assets/profile_pics/paul_s.jpg',
				'assets/profile_pics/vinh_t.jpg',
				'assets/buttons/cancel128.png',
				'assets/buttons/cancel96.png',
				'assets/buttons/cancel24.png',
				'assets/boss1.png',
				'assets/advisor.png',
				'assets/wrench.png',
				'assets/escalator.png'
			];
			
			
			return images;
		}
		
		public static function startLoad(onFinish:Function):void{
			onCompleteCallback = onFinish;
			loadNextImage();
		}
		
		private static function loadNextImage():void{
			var images:Array = getImages();
			var loader:Loader = new Loader();
			var url:String = Game.clientFilesPath + images[imageCounter];
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event):void{
				onLoadComplete(e.currentTarget.content as Bitmap,url);
			});
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(error:IOErrorEvent):void{
				throw error;
			});
				
			loader.load(new URLRequest(url));			
		}
	
		private static function onLoadComplete(bitmap:Bitmap, url:String):void{
			imageCounter++;
			bitmapDataCache[url] = bitmap.bitmapData;
			if(imageCounter == getImages().length){
				onCompleteCallback();
			} else {
				loadNextImage();
			}
		}
		
		public static function getFloorSprite():Sprite{
			var floorSprite:Sprite = new Sprite();
			for(var i:int = 0; i < 50; i++){
				var dispObj:DisplayObject = getImage('assets/grass_block3.png');
				floorSprite.addChild(dispObj);
				dispObj.x = i*dispObj.width;
				dispObj.y -= 15;
			}
			
			return floorSprite;
		}
		
		
		
		
	}
}